package com.lion.seaman.worker.flows;

import org.springframework.util.Assert;

import java.util.HashMap;
import java.util.Map;

public class JobTree {
    Map<String, JobTreeItem> jobFlowMap = new HashMap<>();
    Map<String, String> chdMapping = new HashMap<>();
    private JobTreeItem rootItem;

    private JobTreeItem nextItem;
    private boolean first = true;

    public JobTree add(JobTreeItem item) {
        if (rootItem == null) {
            Assert.isTrue(item.isRoot, "the first item must be root");
            rootItem = item;
            jobFlowMap.put(item.getFlowId(), item);
            if (nextItem == null) {
                reset();
            }
        } else {
            Assert.isTrue(!item.isRoot, "the root item is already exists");
            Assert.notNull(jobFlowMap.get(item.getParentFlowId()), "the parent item is not exists");
            jobFlowMap.put(item.getFlowId(), item);
        }
        chdMapping.put(item.getParentFlowId(), item.getFlowId());
        return this;
    }

    public boolean hasNext() {
        if (first && nextItem != null) {
            return true;
        }
        if (nextItem == null) {
            return false;
        }
        return jobFlowMap.get(chdMapping.get(nextItem.getFlowId())) != null;
    }

    public JobTreeItem next() {
        if (first && nextItem != null) {
            first = false;
            return nextItem;
        }
        return nextItem = jobFlowMap.get(chdMapping.get(nextItem.getFlowId()));
    }

    public JobTree reset() {
        nextItem = rootItem;
        first = true;
        return this;
    }


}
